package com.ruoyi.web.controller.system;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.domain.ReportDetail;
import com.ruoyi.system.domain.ValidationGroups.*;
import com.ruoyi.system.domain.vo.DeviceStatusSummaryVO;
import com.ruoyi.system.domain.vo.QueryVo;
import com.ruoyi.system.domain.vo.SalesSummaryParamVO;
import com.ruoyi.system.domain.vo.SalesSummaryVO;
import com.ruoyi.system.service.IAsyncDetailService;
import com.ruoyi.system.service.IReportDetailService;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/system/report_detail")
public class ReportDetailController extends BaseController {

    @Autowired
    private TokenService tokenService;
    @Autowired
    private ISysDeptService sysDeptService;
    @Autowired
    private IReportDetailService reportDetailService;
    @Autowired
    private IAsyncDetailService asyncDetailService;
    @Autowired
    private ISysUserService sysUserService;

    @PreAuthorize("@ss.hasPermi('system:report_detail:list')")
    @GetMapping("/list")
    public TableDataInfo list(ReportDetail reportDetail) {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
//        reportDetail.setCreateBy(loginUser.getUsername());
        // 设置companyId
        boolean flag = sysDeptService.checkIsCustomer(loginUser.getUser().getDeptId());
        if (flag){
            //当前为客户公司下面用户
            Long customerId = sysDeptService.getCustomerId(loginUser.getUser().getDeptId());
            List<SysUser> sysUsers = sysUserService.queryUserInfo(customerId);
            Set<String> usernames = new HashSet<>();
            if (CollUtil.isNotEmpty(sysUsers)){
                usernames = sysUsers.stream().map(SysUser::getUserName).collect(Collectors.toSet());
            }
            reportDetail.setUsernames(usernames);
        }
        startPage();
        List<ReportDetail> reportDetails = reportDetailService.queryList(reportDetail);
        return getDataTable(reportDetails);
    }

    @PreAuthorize("@ss.hasPermi('system:report_detail:create')")
    @PostMapping("/export_report")
    public AjaxResult exportReport(@RequestBody @Validated(Create.class) ReportDetail reportDetail) {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        // 设置companyId
        Long companyId = sysDeptService.selectCompanyIdByUser(loginUser.getUser());
        reportDetail.setCompanyId(companyId);
        reportDetail.setCreateBy(loginUser.getUsername());
        reportDetail.setCreateTime(new Date());
        reportDetail.setData(JSONUtil.toJsonStr(reportDetail.getChoseData()));
        //设置成手动
        reportDetail.setType("0");
        String tid = asyncDetailService.createTid("报表功能", companyId);
        reportDetail.setTid(tid);
        //先保存数据
        reportDetailService.add(reportDetail);
        reportDetailService.queryDetail(reportDetail, tid, loginUser.getUser());
        return AjaxResult.success(reportDetail);
    }

    /**
     * 膨胀节销售汇总
     *
     * @return
     */
    @PreAuthorize("@ss.hasPermi('system:report_detail:sales_summary')")
    @GetMapping("/sales_summary")
    public AjaxResult salesSummary(SalesSummaryParamVO paramVO) {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        // 设置companyId
        Long companyId = sysDeptService.selectCompanyIdByUser(loginUser.getUser());
        QueryVo queryVo = new QueryVo();
        queryVo.filters.put("company_id",companyId);
        if (paramVO.getMinAmount() != null && paramVO.getMinAmount().compareTo(new BigDecimal(0)) < 0){
            throw new CustomException("合同最小金额不能小于0");
        }
        if (paramVO.getMinAmount() != null && paramVO.getMaxAmount() != null && paramVO.getMinAmount().compareTo(paramVO.getMaxAmount()) > 0){
            throw new CustomException("合同最小金额不能大于合同最大金额");
        }
        queryVo.filters.put("min_amount",paramVO.getMinAmount());
        queryVo.filters.put("max_amount",paramVO.getMaxAmount());
        queryVo.filters.put("code",paramVO.getProjectCode());
        queryVo.filters.put("name",paramVO.getProjectName());
        queryVo.filters.put("dept_id",paramVO.getDeptId());
        queryVo.filters.put("sysUser",loginUser.getUser());
        queryVo.filters.put("peer_code",paramVO.getPeerCode());
        queryVo.filters.put("type",paramVO.getType());
        if (paramVO.getInputTimeStart() != null && paramVO.getInputTimeEnd() != null && paramVO.getInputTimeStart().compareTo(paramVO.getInputTimeEnd()) >= 0){
            throw new CustomException("统计开始时间不能大于或等于统计结束时间");
        }
        queryVo.filters.put("input_time_start",paramVO.getInputTimeStart());
        queryVo.filters.put("input_time_end",paramVO.getInputTimeEnd());
        //startPage();
        List<SalesSummaryVO> salesSummaryVOS = reportDetailService.salesSummary(queryVo);
        return AjaxResult.success(salesSummaryVOS);
    }

    /**
     * 膨胀节状态汇总
     *
     * @return
     */
    @PreAuthorize("@ss.hasPermi('system:report_detail:device_status_summary')")
    @GetMapping("/device_status_summary")
    public TableDataInfo deviceStatusSummary(SalesSummaryParamVO paramVO){
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        // 设置companyId
        Long companyId = sysDeptService.selectCompanyIdByUser(loginUser.getUser());
        QueryVo queryVo = new QueryVo();
        queryVo.filters.put("company_id",companyId);
        queryVo.filters.put("code",paramVO.getProjectCode());
        queryVo.filters.put("sn",paramVO.getSn());
        queryVo.filters.put("name",paramVO.getProjectName());
        queryVo.filters.put("dept_id",paramVO.getDeptId());
        queryVo.filters.put("status",paramVO.getStatus());
        queryVo.filters.put("begin",paramVO.getBegin());
        queryVo.filters.put("end",paramVO.getEnd());
        queryVo.filters.put("type",paramVO.getType());
        queryVo.filters.put("sysUser",loginUser.getUser());
        SysUser sysUser = (SysUser) queryVo.filters.get("sysUser");
        //验证当前用户是否是客户
        Long deptId = null;
        boolean flag = sysDeptService.checkIsCustomer(sysUser.getDeptId());
        if (flag) {
            //取客户部门id
            deptId = sysDeptService.getCustomerId(sysUser.getDeptId());
            queryVo.filters.put("dept_id", deptId);
        }
        startPage();
        List<DeviceStatusSummaryVO> deviceStatusSummaryVOS = reportDetailService.deviceStatusSummary(queryVo);
        return getDataTable(deviceStatusSummaryVOS);
    }
}
